
import 'package:enterprise_v6_app/app/components/custom_app_bar.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

/// 二维码扫描
/// [onScanResult] 扫描结果回调
/// demo:
/// ```dart
/// CustomQrScanPage(
///  onScanResult: (value) {
///      AppToast.show('扫描结果：$value');
///    },
/// );
/// ```
class CustomQrScanPage extends StatefulWidget {
  const CustomQrScanPage({required this.onScanResult, super.key});
  final Function(String) onScanResult;
  @override
  State<CustomQrScanPage> createState() => _CustomQrScanPageState();
}

class _CustomQrScanPageState extends State<CustomQrScanPage> {


  // 扫描控制器
  var controller = MobileScannerController(
    detectionSpeed: DetectionSpeed.normal,
    facing: CameraFacing.back,
    torchEnabled: false,
    autoStart: true,
  );

  // 扫描到的结果
  onSuccess(BarcodeCapture result) {
    final List<Barcode> barcodes = result.barcodes;
    for (var barcode in barcodes) {
      if(barcode.displayValue != null) {
        controller.dispose();
        Get.back();
        AppLogger.log('扫描到:${barcode.displayValue}');
        widget.onScanResult(barcode.displayValue!);
      }
    }

  }

  // 打开手电筒
  openTorch() async {
    await controller.toggleTorch();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        titleText: '二维码扫描',
        actions: [
          // 手电筒
          IconButton(
            icon: const Icon(Icons.flashlight_on),
            onPressed: openTorch,
          ),
        ],
      ),
      body: MobileScanner(
        controller: controller,
        onDetect: onSuccess,
      ),
    );
  }
}
